package com.heatup.apt.api.controller;

import com.heatup.apt.api.service.UserService;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.dao.SmsLogMapper;
import com.heatup.apt.common.util.CheckCodeUtil;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.common.util.SmsUtil;
import com.heatup.apt.model.SmsLog;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping("/checkcode")
public class CheckCodeController extends BaseController{
    private Logger logger = LoggerFactory.getLogger(CheckCodeController.class);
	
    @Autowired
    private UserService userService;
    
    @Autowired
    private SmsLogMapper smsLogMapper;

    /**
     * 发送验证码
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = {RequestMethod.POST, RequestMethod.GET})
    private String send(@RequestParam() String mobile,
						@RequestParam(defaultValue = "") String callback) {
        Integer userId = this.getUserId();

        ApiResultModel<Map<String,Object>> apiResultModel=new ApiResultModel<Map<String,Object>>();
        apiResultModel.setLogined(this.isLogined());    
        
        //未登陆
        if(userId == null){
        	apiResultModel.setRet(ApiResultModel.RET_ERROR);
        	apiResultModel.setMsg("用户未登陆");
        	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
        }
        
        
        try{
        	//检查发送间隔
        	Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
        	if(lastSend != null){
        		long lastSendTime = (long)lastSend;
        		long currentTime = System.currentTimeMillis();
        		long seconds =  (currentTime - lastSendTime)/1000;
        		if(seconds < UserConstants.SEND_CHECK_CODE_INTERVAL){
        			Map<String,Object> map = new HashMap<String,Object>();
        			map.put("nextSendSecond", seconds);
        			apiResultModel.setData(map);
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("验证码发送太频繁");
                    
                    return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
        		}
        	}
        	
        	//检查发送限额
			int todayMyCount = smsLogMapper.querySmsCountByUserMobile(mobile);
			if(todayMyCount > UserConstants.CHECK_CODE_MAX_SEND_COUNT){
        		
        		Map<String,Object> map = new HashMap<String,Object>();
    			apiResultModel.setData(map);
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("已超过今天短信限额");
                
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
    		}
        	
        	Map<String,Object> map = new HashMap<String,Object>();
        	
        	int checkCode = CheckCodeUtil.getCheckCode();
        	boolean sendResult = SmsUtil.sendCheckCode(mobile, checkCode + "");
        	
        	//发送记录
        	SmsLog smsLog = new SmsLog();
        	smsLog.setMobile(mobile);
        	smsLog.setCheckCode(checkCode + "");
        	smsLog.setUserId(userId);
        	smsLog.setSendTime(new Date());
        	smsLog.setSendResult(sendResult?1:2);
        	smsLogMapper.insertSelective(smsLog);
        	
        	this.setSession(SESSION_KEY_MOBILE, mobile);
        	this.setSession(SESSION_KEY_CHECK_CODE, checkCode);
        	this.setSession(SESSION_KEY_CHECK_CODE_LAST_SEND, System.currentTimeMillis());
        	map.put("nextSendSecond", UserConstants.SEND_CHECK_CODE_INTERVAL);
        	
            apiResultModel.setData(map);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("");
        }catch(Exception ex){
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("系统错误" + ex.getMessage());
            logger.error("发送验证码异常",ex);
        }
        //会员价格数据


        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
    }

    /**
     * 校验验证码正确性
     *
     * @param checkCode 验证码
     * @param callback 前端回调
     * @author blank 2017/8/18 下午4:58
     */
    @ResponseBody
    @RequestMapping(value = "/check", method = {RequestMethod.POST, RequestMethod.GET})
    private String checkCheckCode(String checkCode, String callback) {

        Integer userId = this.getUserId();
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(isLogined());
        //未登陆
        if (userId == null) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
        } else {

            try {
                //有效期验证
                Object syscode = this.getSession(SESSION_KEY_CHECK_CODE);
                Object lastSend = this.getSession(SESSION_KEY_CHECK_CODE_LAST_SEND);
                if (syscode == null || lastSend == null) {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("无验证码");
                    return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
                }

                long lastSendTime = (long) lastSend;
                long currentTime = System.currentTimeMillis();
                long seconds = (currentTime - lastSendTime) / 1000;
                if (seconds > UserConstants.CHECK_CODE_TIMEOUT) {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("验证码已失效,请重新发送");
                    return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
                }

                //验证码验证
                if (syscode != null && syscode.toString().equals(checkCode)) {

                    apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
                    apiResultModel.setMsg("验证成功");
                } else {
                    apiResultModel.setRet(ApiResultModel.RET_ERROR);
                    apiResultModel.setMsg("验证码错误");
                }
            } catch (Exception e) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("验证码校验时出错 --->>:" + e  + " 根原因: " + e.getCause());
                logger.error("验证码校验时出错 --->>:" + e  + " 根原因: " + e.getCause());
            }
        }


        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 绑定/全局修改用户手机号
     *
     * @param updateType null|1:只更新用户表 2:全局同步
     * @param callback 前端回调
     * @author blank 2017/8/18 下午5:30
     */
    @RequestMapping("updateMobile")
    @ResponseBody
    public String updateUserMobile(Integer updateType, String callback){

        UserInfo userInfo = getUserInfo();
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>(isLogined());
        //未登陆
        if (userInfo == null) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());

        } else {

            try {
                Object mobile = this.getSession(SESSION_KEY_MOBILE);
                if (updateType == null || updateType == 1) {
                    //保存手机号
                    userService.updateMobile(userInfo.getId(), String.valueOf(mobile));
                } else if (updateType == 2) {
                    userService.syncUserAllMobile(userInfo.getId(), String.valueOf(mobile));
                }

                apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
                apiResultModel.setMsg("更新成功");
            } catch (Exception e) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg("绑定/更新用户手机号出错 ---->>" + e + " 根原因: " + e.getCause());
                logger.error("绑定/更新用户手机号出错 ---->>" + e + " 根原因: " + e.getCause());
            }

        }

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);

    }


}
